package com.xhwl.centiotdata.pushtrigger.light;

import com.xhwl.centiotdata.mq.producer.GeneralProducer;
import com.xhwl.centiotdata.pojo.constant.HuaWeiIoTDAConstant;
import com.xhwl.centiotdata.service.cent.IProjectCentService;
import com.xhwl.common.dto.cent.device.iot.*;
import com.xhwl.common.dto.cent.iotdata.light.LightLoopDTO;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.sdata.Project;
import com.xhwl.common.query.cent.sdata.ProjectQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Author: yanyixiong
 * @Description:
 * @Date: create in 15:47 2022/1/11
 */
@Slf4j
@RestController
public class LightLoopController {

    @Autowired
    IProjectCentService projectCentService;
    @Autowired
    GeneralProducer producer;

    @PostMapping("light-loop/update-switch")
    public ResultJson updateSwitchLoop(@RequestBody IotDeviceJson<DeviceServiceBody<IotSmartLighting>> iotDeviceJson){
        String service_id = iotDeviceJson.getNotify_data().getBody().getServices().get(0).getService_id();
        if(!HuaWeiIoTDAConstant.LIGHT_SERVICE_ID.equalsIgnoreCase(service_id)){
            return ResultJson.success();
        }
        IotSmartLighting iotSmartLighting = iotDeviceJson.getNotify_data().getBody().getServices().get(0).getProperties();
        CommonHeader header = iotDeviceJson.getNotify_data().getHeader();
        String deviceId = header.getDevice_id();
        Integer switchStatus;
        if(Boolean.TRUE.equals(iotSmartLighting.getDO())){
            switchStatus = 1;
        }else{
            switchStatus = 0;
        }
        Map<String,Object> params = new HashMap<>();
        params.put("loopCode",deviceId);
        params.put("switchStatus",switchStatus);
        producer.send("light-loop-update",params);
        return ResultJson.success();
    }

    @PostMapping("light-loop/create-loop")
    public ResultJson addLoop(@RequestBody IotDeviceJson<CreateDeviceBody> iotDeviceJson){
        log.info(iotDeviceJson.toString());
        if (StringUtils.isEmpty(iotDeviceJson)) {
            log.info("推送的数据是空的");
            return ResultJson.fail("推送的数据是空的");
        }
        NotifyData<CreateDeviceBody> notifyData = iotDeviceJson.getNotify_data();
        if ("device".equals(iotDeviceJson.getResource()) && "create".equals(iotDeviceJson.getEvent())) {
            CreateDeviceBody iotDeviceBody = notifyData.getBody();
            if(HuaWeiIoTDAConstant.LIGHT_PRODUCT_ID.equals(iotDeviceBody.getProduct_id())&& HuaWeiIoTDAConstant.LIGHT_PRODUCT_NAME.equals(iotDeviceBody.getProduct_name())){
                IotExtensionInfo extensionInfo = iotDeviceBody.getExtension_info();
                Integer projectId;
                if(Objects.nonNull(extensionInfo)){
                    projectId = extensionInfo.getProjectId();
                }else{
                    try {
                        String projectCode = iotDeviceBody.getDevice_id().split("_")[1];
                        ProjectQuery projectQuery = new ProjectQuery();
                        projectQuery.setCode(projectCode);
                        Project one = projectCentService.getOne(projectQuery, null);
                        projectId = one.getId();
                    }catch (Exception e){
                        projectId = null;
                    }
                }
                LightLoopDTO lightLoop = new LightLoopDTO();
                lightLoop.setProjectId(projectId);
                lightLoop.setLoopCode(iotDeviceBody.getDevice_id());
                lightLoop.setLoopName(iotDeviceBody.getDevice_name());
                lightLoop.setLoopStatus((short) 0);

                try {
                    producer.send("light-loop-create",lightLoop);
                } catch (Exception e) {
                    log.error("iotDA订阅新增智能照明回路，我方新增失败，请查找系统错误原因，报错如下：" + e.getMessage());
                    e.printStackTrace();
                }
            }
        }
        return ResultJson.success();
    }

    @PostMapping("light-loop/remove")
    public ResultJson delLoop(@RequestBody IotDeviceJson iotDeviceJson){

        log.info(iotDeviceJson.toString());
        if (StringUtils.isEmpty(iotDeviceJson)) {
            log.info("推送的数据是空的");
            return ResultJson.success();
        }
        String event = iotDeviceJson.getEvent();
        String resource = iotDeviceJson.getResource();
        NotifyData notifyData = iotDeviceJson.getNotify_data();
        CommonHeader header = notifyData.getHeader();
        if ("device".equals(resource) && "delete".equals(event) && HuaWeiIoTDAConstant.LIGHT_PRODUCT_ID.equals(header.getProduct_id())) {
            String iotDeviceId = header.getDevice_id();
            try {
                Map<String,Object> params = new HashMap<>();
                params.put("loopCode",iotDeviceId);
                producer.send("light-loop-remove",params);
            } catch (Exception e) {
                log.error("iotDA订阅删除智能照明回路，我方删除失败，请查找系统错误原因，报错如下：" + e.getMessage());
                e.printStackTrace();
            }
        }
        return ResultJson.success();
    }



}
